package com.cxz.kotlin.baselibs.http.gsondefaultadapter

import com.google.gson.*
import java.lang.Exception
import java.lang.NumberFormatException
import java.lang.reflect.Type

class DoubleDefaultAdapter(var default: Double) : JsonSerializer<Double>, JsonDeserializer<Double> {
    @Throws(JsonParseException::class)
    override fun deserialize(
        json: JsonElement,
        typeOfT: Type?,
        context: JsonDeserializationContext?
    ): Double? {
        try {
            if (json.asString == "" || json.asString == "null") { //定义为double类型,如果后台返回""或者null,则返回0.00
                return default
            }
        } catch (ignore: Exception) {
        }
        return try {
            json.asDouble
        } catch (e: NumberFormatException) {
            //            throw new JsonSyntaxException(e);
            default
        }
    }

    override fun serialize(
        src: Double?,
        typeOfSrc: Type?,
        context: JsonSerializationContext?
    ): JsonElement? {
        return JsonPrimitive(src)
    }
}